package com.zhaoyd.uaademo.config.security.integration;

import com.zhaoyd.uaademo.config.security.MyUserDetail;
import com.zhaoyd.uaademo.config.security.integration.exception.AuthenticatorNotFoundException;
import com.zhaoyd.uaademo.entity.SysUser;
import com.zhaoyd.uaademo.service.SysResourceService;
import com.zhaoyd.uaademo.service.SysRoleService;
import com.zhaoyd.uaademo.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * @author zhaoyd
 * @date 2020-10-31 19:44
 */
@Component
public class IntegrationUserDetailService implements UserDetailsService {
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysResourceService sysResourceService;
    @Autowired
    private List<AbstractIntegrationAuthenticator> integrationAuthenticators;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        IntegrationAuthentication integrationAuthentication = IntegrationAuthenticationContext.get();
        if(integrationAuthentication == null){
            //非集成登录，username-password登录
            return this.loadUserByUsernameDefault(username);
        }
        //集成登录，调用IntegrationAuthenticator认证
        UserDetails userDetails = this.loadUserByIntegration(integrationAuthentication);

        return userDetails;

    }

    private MyUserDetail loadUserByIntegration(IntegrationAuthentication integrationAuthentication) {
        if (this.integrationAuthenticators != null) {
            for (AbstractIntegrationAuthenticator authenticator : integrationAuthenticators) {
                if (authenticator.support(integrationAuthentication)) {
                    MyUserDetail myUserDetail =  authenticator.authenticate(integrationAuthentication);
                    //如果密码不为空，覆盖密码， 后期密码不验证
                    if(integrationAuthentication.getPassword() != null) {
                        myUserDetail.setPassword(passwordEncoder.encode(integrationAuthentication.getPassword()));
                        //userDetail.getSysUser().setPassword(passwordEncoder.encode(integrationAuthentication.getPassword()));
                    }
                    return myUserDetail;
                }
            }
        }

        throw new AuthenticatorNotFoundException("未找到合法的集成登录认证器:"+integrationAuthentication.getAuthType());
    }

    /**
     * 普通用户名密码登录
     * @param username
     * @return
     */
    private UserDetails loadUserByUsernameDefault(String username){
        SysUser sysUser = sysUserService.findByUsername(username);
        if(sysUser == null){
            throw new UsernameNotFoundException(username);
        }
        Set<String> roleCodes = sysRoleService.listRoleCodeByUser(sysUser.getId());
        Set<String> resourceCodes = sysResourceService.listResourceCodeByUser(sysUser.getId());
        return MyUserDetail.build(sysUser, roleCodes, resourceCodes);
    }


}
